package com.sgu6.netty.handler;


import android.util.Log;

import com.sgu6.netty.event.LoginAdminEvent;
import com.sgu6.netty.protobuffer.NettyMessageProto;

import org.greenrobot.eventbus.EventBus;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;


public class LoginAdminHandler extends ChannelHandlerAdapter {

    protected final String TAG = LoginAdminHandler.class.getSimpleName();

    public LoginAdminHandler() {

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        Log.i(TAG, "channelActive: ");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessageProto.NettyMessage packet = (NettyMessageProto.NettyMessage) msg;
        if (packet.getHeader() != null && packet.getHeader().getType() == NettyMessageProto.Header.Type.LOGIN_ADMIN) {
            EventBus.getDefault().post(new LoginAdminEvent());
        } else {
            ctx.fireChannelRead(msg);
        }
    }


    @Override
    public void close(ChannelHandlerContext ctx, ChannelPromise promise) {
        Log.i(TAG, "close: ");
        ctx.close(promise);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Log.i(TAG, "channelInactive: ");
    }

    @Override
    public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        ctx.disconnect(promise);
        Log.i(TAG, "disconnect: ");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Log.i(TAG, "exceptionCaught: ");
        Channel channel = ctx.channel();
        cause.printStackTrace();
        if (channel.isActive()) {
            Log.i(TAG, "exceptionCaught: client" + channel.remoteAddress() + "异常");
        }
    }

}
